using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Text;
using Newtonsoft.Json.Serialization;

namespace IQIGame.Onigao.GamePlay
{
    public class JsonHelper
    {
        private static Encoding _UTF8 = new UTF8Encoding(false);
        private static JsonSerializerSettings settings;

        static JsonHelper()
        {
            settings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Auto,
                ContractResolver = new NoGetPropertyResolver(),
                //Converters = { new EntityParamDictionaryConverter(), new RectIntJsonConverter() }
            };
        }

        class NoGetPropertyResolver : DefaultContractResolver
        {
            protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
            {
                return base.CreateProperties(type, memberSerialization).Where((x) => x.Writable).ToList();
            }
        }

        public static T DeserializeJson<T>(string json)
        {
            return DeserializeJson<T>(json, settings);
        }

        public static T DeserializeJson<T>(byte[] byteArray)
        {
            return DeserializeJson<T>(byteArray, settings);
        }

        public static string SerializeObject(object value)
        {
            return SerializeObject(value, settings);
        }

        public static T DeserializeJson<T>(string json, JsonSerializerSettings settings)
        {
            return JsonConvert.DeserializeObject<T>(json, settings);
        }

        public static T DeserializeJson<T>(byte[] byteArray, JsonSerializerSettings settings)
        {
            return JsonConvert.DeserializeObject<T>(_UTF8.GetString(byteArray), settings);
        }

        public static string SerializeObject(object value, JsonSerializerSettings settings)
        {
            return JsonConvert.SerializeObject(value, settings);
        }
    }
}